<template>
  <!-- 微信授权中间页 -->
  <view class="middle_page"></view>
</template>

<script>
import Config from '@/config/config.conf';
export default {
  components: {},
  data() {
    return {};
  },
  computed: {},
  async onLoad(e) {
    console.log('跳转回中间页,code:', e.code);
    console.log('跳转回中间页,token:', e.token);
    let originPage = uni.getStorageSync('originPage');
    if (e.code) {
      
      
      // 微信浏览器，通过code获取token
      let res = await this.getUserInfo(e.code);
      console.log('token1: ', res.data.token);
      if (res.data.token) {
        // 存储token
        uni.setStorageSync('token', res.data.token)
      }
      // 初始化OSS信息
      this.$api.common.initSystem({version: Config.version}).then(res => {
        this.$store.state.system.ossLink = res.data.uploaddata.cdnurl
        this.$store.state.system.uploadApi = res.data.uploaddata.uploadurl
        
        if(res.data.user && res.data.user.mobile && res.data.user.nickname){
          // 已经完善用户信息
          console.log('跳转入之前页面的url：', '/' + (originPage || ''))
          uni.removeStorageSync('originPage');
          uni.redirectTo({
            url: '/' + (originPage || '')
          });
        }else{
          // 跳转完善资料页
          uni.redirectTo({
            url: '/pages/user/register/index'
          });
        }
      })
      
      
    } else if (e.token) {
      // 非微信浏览器
      this.$api.common.initSystem({version: Config.version}).then(res => {
        this.$store.state.system.ossLink = res.data.uploaddata.cdnurl
        this.$store.state.system.uploadApi = res.data.uploaddata.uploadurl
        uni.redirectTo({
          url: '/'
        });
      })
    }
  },
  methods: {
    getUserInfo(code) {
      return new Promise((resolve, reject) => {
        this.$api.user
          .getTokenByCode({ code: code })
          .then(res => {
            resolve(res); //resolve在promise执行器内部
          })
          .catch(err => {
            console.log('中间页获取用户');
            reject(err);
          });
      });
    }
  }
};
</script>

<style scoped lang="scss"></style>
